package cn.edu.zafu.bigdata.x.zyy;

//服务端代码（TimeServer.java）
import java.net.*;
import java.io.*;
import java.util.Date;

class TimeServer {
    public static void main(String[] args) {
        try {
            // 创建服务器端的DatagramSocket，监听端口号1234
            DatagramSocket serverSocket = new DatagramSocket(1234);
            System.out.println("Time server is running and waiting for client request...");

            // 服务器无限循环，等待客户端请求
            while (true) {
                // 准备接收请求的缓冲区
                byte[] receiveBuffer = new byte[1024];
                // 创建DatagramPacket对象，用于接收客户端请求
                DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);

                // 接收客户端请求
                serverSocket.receive(receivePacket);
                // 获取客户端地址和端口
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                // 获取当前时间
                Date now = new Date();
                String currentTime = now.toString();

                // 将时间字符串转换为字节数组
                byte[] sendBuffer = currentTime.getBytes();
                // 创建DatagramPacket对象，用于发送时间给客户端
                DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);

                // 发送时间给客户端
                serverSocket.send(sendPacket);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//客户端代码（TimeClient.java）
public class TimeClient {
    public static void main(String[] args) {
        try {
            // 创建客户端的DatagramSocket
            DatagramSocket clientSocket = new DatagramSocket();
            System.out.println("Time client is running and sending request to server...");

            // 准备发送请求的缓冲区
            byte[] sendBuffer = "Current time?".getBytes();
            // 获取服务器地址和端口
            InetAddress serverAddress = InetAddress.getByName("服务器的IP地址"); // 替换为服务端的实际IP地址
            int serverPort = 1234;

            // 创建DatagramPacket对象，用于发送请求到服务器
            DatagramPacket sendPacket = new DatagramPacket(sendBuffer, sendBuffer.length, serverAddress, serverPort);

            // 发送请求到服务器
            clientSocket.send(sendPacket);

            // 准备接收服务器响应的缓冲区
            byte[] receiveBuffer = new byte[1024];
            // 创建DatagramPacket对象，用于接收服务器响应
            DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, receiveBuffer.length);

            // 接收服务器响应
            clientSocket.receive(receivePacket);

            // 将响应字符串转换为字符串
            String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Server time: " + response);

            // 关闭客户端DatagramSocket
            clientSocket.close();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
